package com.tools.module.base.service.impl;

import com.tools.common.dynamicquery.DynamicQuery;
import com.tools.common.model.PageBean;
import com.tools.common.model.Result;
import com.tools.common.util.DateUtils;
import com.tools.module.base.repository.BaseResourceRepository;
import com.tools.module.base.entity.BaseResource;
import com.tools.module.base.service.BaseResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BaseResourceServiceImpl implements BaseResourceService {

    @Autowired
    private DynamicQuery dynamicQuery;
    @Autowired
    private BaseResourceRepository resourceRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result save(BaseResource resource) {
        resource.setUpdateTime(DateUtils.getTimestamp());
        resourceRepository.saveAndFlush(resource);
        return Result.ok("保存成功");
    }

    @Override
    public Result get(Long id) {
        BaseResource resource = resourceRepository.getOne(id);
        return Result.ok(resource);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result delete(Long id) {
        resourceRepository.deleteById(id);
        return Result.ok("删除成功");
    }

    @Override
    public Result list(BaseResource resource) {
        String nativeSql = "SELECT COUNT(*) FROM base_resource where service_id =" + "\"" + resource.getServiceId() + "\"";
        Long count = dynamicQuery.nativeQueryCount(nativeSql);
        PageBean<BaseResource> data = new PageBean<>();
        if (count > 0) {
            nativeSql = "SELECT * FROM base_resource where service_id =? ORDER BY seq";
            Pageable pageable = PageRequest.of(resource.getPageNo(), resource.getPageSize());
            List<BaseResource> list = dynamicQuery.nativeQueryPagingList(BaseResource.class, pageable, nativeSql, resource.getServiceId());
            data = new PageBean(list, count);
        }
        return Result.ok(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateSeq(BaseResource resource ) {
        String nativeSql = "update base_resource set seq = seq +1 where seq >= ? and service_id = ?";
        dynamicQuery.nativeExecuteUpdate(nativeSql,resource.getSeq(),resource.getServiceId());
        return Result.ok("修改成功");
    }

    @Override
    public Long queryBySeq(BaseResource resource) {
        String nativeSql = "SELECT COUNT(*) FROM base_resource where  service_id =" + "\"" + resource.getServiceId() + "\""+ "and seq = "+resource.getSeq();
        Long count = dynamicQuery.nativeQueryCount(nativeSql);

        return count;
    }
}
